package com.hbnu.config;

import com.hbnu.service.VideoService;
import com.hbnu.tourist.domain.Tourist;
import com.hbnu.video.domain.Video;
import com.ruoyi.common.core.domain.AjaxResult;
import io.minio.GetPresignedObjectUrlArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.http.Method;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/tourists/personal")
@Slf4j
public class PersonalTouristController {
    @Autowired
    private MinioClient minioClient;

    @Autowired
    private VideoService videoService;

    @PostMapping("/uploadVideo")
    public AjaxResult uploadVideo(@RequestParam MultipartFile file) throws Exception {
        Tourist loginUser = (Tourist) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        Long touristId = loginUser.getId();  // 假设是这样命名的
        String originalFileName = file.getOriginalFilename();
        String extension = FilenameUtils.getExtension(originalFileName);
        log.info("文件名：{}", originalFileName);
        log.info("扩展名：{}", extension);
        String fileName = touristId + "-" + System.currentTimeMillis() + "." + extension;
        String bucket = "video";

        // 上传文件到 MinIO
        minioClient.putObject(
                PutObjectArgs.builder()
                        .bucket(bucket)
                        .object(fileName)
                        .stream(file.getInputStream(), file.getSize(), -1)
                        .contentType(file.getContentType())
                        .build()
        );

        // 生成访问链接
        String url = minioClient.getPresignedObjectUrl(
                GetPresignedObjectUrlArgs.builder()
                        .bucket(bucket)
                        .object(fileName)
                        .method(Method.GET)
                        .expiry(60 * 60) // 1 小时有效
                        .build()
        );

        // 将视频路径存入数据库
        Video video = new Video();
        video.setUserId(touristId);
        video.setVideoUrl(url);
        video.setTitle(fileName);
        videoService.save(video);

        return AjaxResult.success("上传成功", url);
    }
}
